from PyQt5.QtWidgets import (
    QDialog, QVBoxLayout, QHBoxLayout, QFormLayout,
    QLineEdit, QTextEdit, QComboBox, QPushButton,
    QLabel, QDialogButtonBox
)
from PyQt5.QtCore import Qt
from models.task import Task, Priority


class TaskDialog(QDialog):
    """任务编辑对话框"""
    
    def __init__(self, parent=None, task=None):
        super().__init__(parent)
        self.task = task
        self.is_edit_mode = task is not None
        self.init_ui()
        self.setup_connections()
        
        if self.is_edit_mode:
            self.load_task_data()
    
    def init_ui(self):
        """初始化用户界面"""
        self.setWindowTitle("编辑任务" if self.is_edit_mode else "添加任务")
        self.setModal(True)
        self.resize(400, 300)
        
        # 主布局
        layout = QVBoxLayout()
        
        # 表单布局
        form_layout = QFormLayout()
        
        # 任务标题
        self.title_edit = QLineEdit()
        self.title_edit.setPlaceholderText("请输入任务标题")
        form_layout.addRow("标题*:", self.title_edit)
        
        # 任务描述
        self.description_edit = QTextEdit()
        self.description_edit.setPlaceholderText("请输入任务描述（可选）")
        self.description_edit.setMaximumHeight(100)
        form_layout.addRow("描述:", self.description_edit)
        
        # 优先级
        self.priority_combo = QComboBox()
        self.priority_combo.addItems([p.value for p in Priority])
        self.priority_combo.setCurrentText(Priority.MEDIUM.value)
        form_layout.addRow("优先级:", self.priority_combo)
        
        layout.addLayout(form_layout)
        
        # 按钮
        button_box = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel
        )
        
        # 自定义按钮文本
        ok_button = button_box.button(QDialogButtonBox.Ok)
        cancel_button = button_box.button(QDialogButtonBox.Cancel)
        ok_button.setText("保存")
        cancel_button.setText("取消")
        
        layout.addWidget(button_box)
        
        self.setLayout(layout)
        self.button_box = button_box
        
        # 设置焦点
        self.title_edit.setFocus()
    
    def setup_connections(self):
        """设置信号连接"""
        self.button_box.accepted.connect(self.accept)
        self.button_box.rejected.connect(self.reject)
        
        # 标题输入变化时检查有效性
        self.title_edit.textChanged.connect(self.validate_input)
        
        # 初始验证
        self.validate_input()
    
    def validate_input(self):
        """验证输入有效性"""
        title = self.title_edit.text().strip()
        ok_button = self.button_box.button(QDialogButtonBox.Ok)
        ok_button.setEnabled(bool(title))
    
    def load_task_data(self):
        """加载任务数据到表单"""
        if self.task:
            self.title_edit.setText(self.task.title)
            self.description_edit.setPlainText(self.task.description)
            self.priority_combo.setCurrentText(self.task.priority.value)
    
    def get_task_data(self):
        """获取表单数据"""
        title = self.title_edit.text().strip()
        description = self.description_edit.toPlainText().strip()
        priority_text = self.priority_combo.currentText()
        priority = Priority(priority_text)
        
        return {
            'title': title,
            'description': description,
            'priority': priority
        }
    
    def accept(self):
        """确认对话框"""
        if not self.title_edit.text().strip():
            return
        super().accept()
    
    @staticmethod
    def add_task(parent=None):
        """静态方法：添加任务"""
        dialog = TaskDialog(parent)
        if dialog.exec_() == QDialog.Accepted:
            return dialog.get_task_data()
        return None
    
    @staticmethod
    def edit_task(parent=None, task=None):
        """静态方法：编辑任务"""
        dialog = TaskDialog(parent, task)
        if dialog.exec_() == QDialog.Accepted:
            return dialog.get_task_data()
        return None